<?php

namespace app\common\model;

use app\common\model\SystemRegion;
use app\common\basic\BaseModel;
use app\common\event\CustomerChanged;
use Webman\Event\Event;

/**
 * 部门模型
 */
class CrmCustomers extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';
    protected $table = 'vk_crm_customers';

    // 字段映射
    public static $fieldLabels = [
        'user_id' => '跟进人',
        'avatar' => '头像',
        'stage' => '客户阶段',
        'province_id' => '省份',
        'city_id' => '城市',
        'area_id' => '区域',
        'lat' => '纬度',
        'lng' => '经度',
        'status' => '状态',
        'follow_up_time' => '跟进时间',
        'sign_time' => '签约时间',
    ];

    public function metas()
    {
        return $this->hasMany(CrmCustomerMetas::class, 'customer_id');
    }
    
    public function follows()
    {
        return $this->hasMany(CrmFollowUps::class, 'customer_id');
    }

    public function user()
    {
        return $this->belongsTo(SystemUser::class, 'user_id')->field('id,username,nickname,avatar');
    }
    
    public function creator()
    {
        return $this->belongsTo(SystemUser::class, 'created_by')->field('id,username,nickname,avatar');
    }

    public function attachment()
    {
        return $this->hasMany(CrmCustomerAttachment::class, 'customer_id')->field('id,customer_id,type, src, mime, filename,create_time');
    }

    public function getRegionAttr($value, $data)
    {
        // 根据省市区id获取名称
        $regionData = SystemRegion::whereIn('id', [$data['province_id'], $data['city_id'], $data['area_id']])->column('name', 'id');
        $regionNames = [];
        if (!empty($regionData[$data['province_id']])) {
            $regionNames[] = $regionData[$data['province_id']];
        }
        if (!empty($regionData[$data['city_id']])) {
            $regionNames[] = $regionData[$data['city_id']];
        }
        if (!empty($regionData[$data['area_id']])) {
            $regionNames[] = $regionData[$data['area_id']];
        }
        return implode('-', $regionNames);
    }
    
    public function getProvinceAttr($value, $data)
    {
        if (!empty($data['province_id'])) {
            return SystemRegion::where('id', $data['province_id'])->value('name');
        }
        return '';
    }   
    
    public function getCityAttr($value, $data)
    {
        if (!empty($data['city_id'])) {
            return SystemRegion::where('id', $data['city_id'])->value('name');
        }
        return '';
    }
    
    public function getAreaAttr($value, $data)
    {
        if (!empty($data['area_id'])) {
            return SystemRegion::where('id', $data['area_id'])->value('name');
        }
        return '';
    }
    
}